#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen@163.com
@file: users.py
@time: 2023/11/17 16:56
@desc: 
"""
import bcrypt
from sqlalchemy.orm import defer

from backend.tvadmin.system.models.permission import Menu, Role, User, Dept
from backend.tvadmin.utils.base_requeset import BaseAuthCheckHttpHandler
from backend.tvadmin.utils.base_response import SuccessResponse, ErrorResponse
from backend.tvadmin.utils.page_utils import self_pagination


class UserModelViewSet(BaseAuthCheckHttpHandler):
    """
    用户管理
    """

    def get(self, *args, **kwargs):
        if hasattr(self.request, "data"):
            result = User.filter_list(self.request.data)
        else:
            result = User.all_list()
        data = self_pagination(self.request, data_list=result)
        return self.write(SuccessResponse(data))

    def post(self, *args, **kwargs):
        """
        用户添加
        """
        password = self.request.data.get("password")
        if password:
            hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
            request_data = self.request.data
            request_data["password"] = hashed_password
            user_obj = User(**request_data)
            if hasattr(self.request.data, "roles"):
                roles = self.request.data.get("roles")
                user_obj.roles = Role.filter_in(key="id", filter=roles)
            user = User.add(user_obj, self.request)
            return self.write(SuccessResponse(user))

    def put(self, *args, **kwargs):
        """
        用户修改
        """
        id = self.request.data.get("id")
        if id:
            user = User.first(id=id)
            if user:
                user.name = self.request.data.get("name")
                roles = self.request.data.get("roles")
                roles = Role.filter_in(key="id", filter=roles)
                dept_id = self.request.data.get("dept_id")
                dept = Dept.first(id=dept_id)
                if roles:
                    user.roles = roles
                if dept:
                    user.dept = dept
                User.save(user)
                return self.write(SuccessResponse())

    def delete(self, *args, **kwargs):
        """
        删除用户
        """
        id = self.request.data.get("id")
        user = User.first(id=id)
        if user:
            Role.delete_soft(id=id)
            return self.write(SuccessResponse(data=[]))
        else:
            return self.write(ErrorResponse(msg="用户不存在不存在"))
